# -*- coding: UTF-8 -*-
import json
import web
from controller import message
from controller import verify
from manager import hot_news_manager
from bean.hot_new_message import HotNewMessage
from collections import namedtuple
import traceback
from utils import hot_new_utils
from chatgpt import completions

urls = ("/hot_news_web/.*", "HotNews")
base_url = "/hot_news_web"
app = web.application(urls, globals())


class HotNews:

    def GET(self):
        path = web.ctx.path
        path = path.replace(base_url, '', 1)
        print(path)
        if path == '/message':
            return message.receive(web)
        elif path == '/news/query':
            param = web.input()
            hot_news_type = param.get('type')
            result = hot_news_manager.query(hot_news_type)
            print(result)
            return hot_new_utils.to_json_str(result)
        elif path == '/news/save':
            return "save"
        elif path == '/types/query':
            return hot_new_utils.to_json_str(hot_news_manager.query_all_types())
        return verify.verify(web)

    def POST(self):
        path = web.ctx.path
        path = path.replace(base_url, '', 1)
        if path == '/news/save':
            key = 'message'
            data = json.loads(str(web.data(), "utf-8"))
            try:
                hot_msg: HotNewMessage = json.loads(json.dumps(data[key]), object_hook=custom_decoder)
                hot_news_manager.save(hot_msg)
            except Exception as e:
                print(traceback.format_exc())
                return e
            # print(data.pop("hot_news"))
            return "success"
        elif path == '/completions':
            data = json.loads(str(web.data(), "utf-8"))
            return completions.chat(data['text'])
        else:
            return "not such method"


if __name__ == '__main__':
    app.run()


def custom_decoder(obj_dict):
    return namedtuple('X', obj_dict.keys())(*obj_dict.values())
